package com.jcark.ui.view.textview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.jcark.ui.R

/**
 * Description:自定义的文本编辑控件 <br>
 * @author King.Zi<br>
 * @date 2024/10/8<br>
 * Email: 78688689@qq.com
 */
open class MEditText : AppCompatEditText {
    companion object {
        const val Thin = 4
        const val ExtraLight = 5
        const val Light = 6
        const val Regular = 7
        const val Medium = 8
        const val SemiBold = 9
        const val Bold = 10
        const val ExtraBold = 11
        const val Black = 12
    }

    private var mTypeFaceValue = 0
    private var mFontWeight = -1
    private var mTypefaceArray = arrayListOf(
        Thin,
        ExtraLight,
        Light,
        Regular,
        Medium,
        SemiBold,
        Bold,
        ExtraBold,
        Black
    )

    constructor(context: Context?) : super(context!!)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        getAttrs(context, attrs)
    }

    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        getAttrs(context, attrs)
    }

    private fun getAttrs(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MEditTextView)
        mTypeFaceValue = typedArray.getInt(R.styleable.MEditTextView_metv_external_typeface, 0)
        mFontWeight = typedArray.getInt(R.styleable.MEditTextView_metv_external_font_weight, -1)
        if (mFontWeight > 3) {
            mTypeFaceValue = mFontWeight
        }
        typedArray.recycle()
    }


    override fun onDraw(canvas: Canvas) {
        if (mTypeFaceValue in mTypefaceArray) {
            when (mTypeFaceValue) {
                Thin -> paint.strokeWidth = 0.4f //100
                ExtraLight -> paint.strokeWidth = 0.5f //200
                Light -> paint.strokeWidth = 0.6f //300
                Regular -> paint.strokeWidth = 0.0f //400
                Medium -> paint.strokeWidth = 0.8f //500
                SemiBold -> paint.strokeWidth = 1f //600
                Bold -> paint.strokeWidth = 1.2f //700
                ExtraBold -> paint.strokeWidth = 1.3f //800
                Black -> paint.strokeWidth = 2f //900
            }
            paint.style = Paint.Style.FILL_AND_STROKE
        }
        super.onDraw(canvas)
    }

    fun setTextStyleType(typeFace: Int) {
        mTypeFaceValue = typeFace
        super.setTypeface(typeface)
        postInvalidate()
    }

    fun isEmpty(): Boolean {
        return text?.isEmpty() == true
    }

    fun getLength(): Int {
        return text?.length ?: 0
    }
}